package com.bridgeintelligent.tag.engine.parse;

import com.bridgeintelligent.tag.engine.api.BaseCode;
import com.bridgeintelligent.tag.engine.api.DimInfo;
import com.bridgeintelligent.tag.engine.api.EngineConfig;
import com.bridgeintelligent.tag.engine.api.QueryModel;
import com.bridgeintelligent.tag.engine.api.rsp.DataSetRsp;
import com.bridgeintelligent.tag.engine.api.theme.ThemeDetailResult;
import com.bridgeintelligent.tag.engine.core.cache.CacheConfig;
import com.bridgeintelligent.tag.engine.core.cache.CacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.*;

/**
 * Created by JackCheung on 2019/10/15 8:54 PM.
 */
@Slf4j
public class DataSetParse extends BaseParse {

    private static final String DATE_FORMAT = "%s-%s";

    /**
     * 创建返回数据DataSetRsp
     *
     * @param queryModel
     * @param searchResponse 查询结果
     * @param fieldsSet      字段集
     * @return DataSetRsp
     */
    public static DataSetRsp create(QueryModel queryModel, SearchResponse searchResponse, List<String> fieldsSet) {

        DataSetRsp dataSetRsp = new DataSetRsp();
        SearchHits searchHits = searchResponse.getHits();
        long count = searchHits.getTotalHits().value;
        DataSetRsp.DataRsp dataRsp = new DataSetRsp.DataRsp();
        dataRsp.setTotalElements(count);
        dataRsp.setSize((int) Math.ceil((double) count / queryModel.getSize()));
        //根据fieldsSet解析数据并设置content
        dataRsp.setContent(parseHandler(searchHits, fieldsSet, queryModel.getFieldsDataDate()));
        dataRsp.setDims(parseId(queryModel.getFields()));
        dataSetRsp.setCode(BaseCode.SUCCESS);
        dataSetRsp.setData(dataRsp);
        return dataSetRsp;
    }

    private static Map<String, DimInfo> parseId(List<String> fields){
        if(CollectionUtils.isEmpty(fields)){
            return Collections.emptyMap();
        }
        Map<String, DimInfo> mapping = new HashMap<>();
        fields.forEach(s->{
            if ( StringUtils.equalsIgnoreCase( s, EngineConfig.CUST_NO ) ) {
                return;
            }
            DimInfo dimInfo = CacheUtils.getCacheInfo(CacheConfig.DIM_INFO, s);
            if ( dimInfo != null ) {
                mapping.put(dimInfo.getDimName(), dimInfo);
            }
        });
        return mapping;
    }

    /**
     * 解析数据
     *
     * @param searchHits searchHits
     * @param fieldsSet  字段集
     * @return List<Map < String, String>>
     */
    private static List<Map<String, String>> parseHandler(SearchHits searchHits, List<String> fieldsSet, String dataDate) {
        SearchHit[] hits = searchHits.getHits();
        List<Map<String, String>> result = new ArrayList<>(hits.length);
        for (SearchHit searchHit : hits) {
            //得到sourceMap
            Map<String, Object> sourceMap = searchHit.getSourceAsMap();
            Map<String, String> tempMap = new LinkedHashMap<>(sourceMap.size());
            //查询缓存，把编号转换为实际的值，放入tempMap中
            commonParse(fieldsSet, sourceMap, tempMap,dataDate);
            result.add(tempMap);
        }
        return result;
    }

    public static ThemeDetailResult themeDetailQuery(SearchResponse searchResponse, int size, List<String> fieldsSet , String dataDate) {
        ThemeDetailResult result = ThemeDetailResult.of();
        SearchHits searchHits = searchResponse.getHits();
        long count = searchHits.getTotalHits().value;
        ThemeDetailResult.R data = ThemeDetailResult.R.of()
                .setTotalPage((int) Math.ceil((double) count / size))
                .setTotalElements(count)
                .setSize(size)
                .setContent(parseHandler(searchHits, fieldsSet, dataDate));
        result.setCode(BaseCode.SUCCESS);
        result.setData(data);
        return result;
    }
}
